package com.ffcs.crmd.tsp.server.netty.processor;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ffcs.crmd.tsp.api.dto.client.TspJobDetailRunning;
import com.ffcs.crmd.tsp.api.dto.netty.RemotingCommand;
import com.ffcs.crmd.tsp.api.netty.INettyProcessor;
import com.ffcs.crmd.tsp.common.constant.LoggerName;
import com.ffcs.crmd.tsp.common.netty.ResponseCode;
import com.ffcs.crmd.tsp.core.util.XmlUtil;
import com.ffcs.crmd.tsp.server.application.ApplicationManagerHolder;
import com.ffcs.crmd.tsp.server.core.DataBaseHandler;
import com.ffcs.crmd.tsp.server.core.RemotingHandler;
import com.ffcs.crmd.tsp.server.jdbc.entity.Job;
import com.ffcs.crmd.tsp.server.jdbc.entity.JobDetail;
import com.ffcs.crmd.tsp.server.jdbc.entity.JobGroup;
import com.ffcs.crmd.tsp.server.job.info.JobDetailShell;
import com.ffcs.crmd.tsp.server.manager.JobProcessManager;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

/**
 * 
 * 功能说明:清除死任务处理者
 *
 * @author ZHONGFUHUA
 * 
 * @since 1.0.0-SNAPSHOT
 *
 */
public class DeleteJobDetailRunningProcessor implements INettyProcessor {
    
    /**
     * 日志
     */
    private final static Logger LOG               = LoggerFactory.getLogger(LoggerName.RemotingLoggerName);
    
    /**
     * 日志
     */
    private final static Logger LOG_SERVER        = LoggerFactory.getLogger(LoggerName.ServerLoggerName);
    
    /**
     * 任务数据库服务
     */
    private DataBaseHandler     dataBaseHandler;
    
    /**
     * 任务端管理器
     */
    private JobProcessManager   jobProcessManager = ApplicationManagerHolder.getBean("jobProcessManager", JobProcessManager.class);
    
    /**
     * 功能说明:
     * 
     * @param remotingController
     */
    public DeleteJobDetailRunningProcessor(RemotingHandler remotingController, DataBaseHandler dataBaseHandler) {
        this.dataBaseHandler = dataBaseHandler;
    }
    
    @Override
    public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) {
        RemotingCommand response = RemotingCommand.createResponseCommand(ResponseCode.SUCCESS);
        String requestXml = new String(request.getBody());
        try {
            LOG.info("SERVER-NETTY: one request to delete running job detail is received that body=[{}]", requestXml);
            TspJobDetailRunning tspJobDetailRunning = (TspJobDetailRunning) XmlUtil.fromXml(requestXml, TspJobDetailRunning.class);
            List<Job> jobList = new ArrayList<Job>();
            if (StringUtils.isNoneBlank(tspJobDetailRunning.getJobGroupName())) {
                JobGroup jobGroupParam = new JobGroup();
                jobGroupParam.setName(tspJobDetailRunning.getJobGroupName());
                jobGroupParam.setClusterName(tspJobDetailRunning.getClusterName());
                JobGroup jobGroup = dataBaseHandler.getServiceSupport().getJobGroup(jobGroupParam);
                
                if(jobGroup != null){
                    Job jobParam = new Job();
                    jobParam.setJobGroupId(jobGroup.getId());
                    jobList.addAll(dataBaseHandler.getServiceSupport().queryJob(jobParam));
                }
            } else if (StringUtils.isNoneBlank(tspJobDetailRunning.getJobName())) {
                Job jobParam = new Job();
                jobParam.setName(tspJobDetailRunning.getJobName());
                jobParam.setClusterName(tspJobDetailRunning.getClusterName());
                jobList.add(dataBaseHandler.getServiceSupport().getJob(jobParam));
            } else if (StringUtils.isNoneBlank(tspJobDetailRunning.getJobDetailName())) {
                JobDetail jobDetailParam = new JobDetail();
                jobDetailParam.setName(tspJobDetailRunning.getJobDetailName());
                jobDetailParam.setClusterName(tspJobDetailRunning.getClusterName());
                JobDetail jobDetail = dataBaseHandler.getServiceSupport().getJobDetail(jobDetailParam);
                
                Job jobParam = new Job();
                jobParam.setId(jobDetail.getJobId());
                jobList.add(dataBaseHandler.getServiceSupport().getJob(jobParam));
            }
            
            for (Job job : jobList) {
                List<JobDetailShell> jobDetailShellList = jobProcessManager.getJobDetailRunning(job.getName());
                for (JobDetailShell jobDetailShell : jobDetailShellList) {
                    if(StringUtils.isNoneBlank(tspJobDetailRunning.getJobDetailName()) && 
                        !tspJobDetailRunning.getJobDetailName().equals(jobDetailShell.getJobDetailName())){
                        continue;
                    }
                    
                    if(StringUtils.isNoneBlank(tspJobDetailRunning.getId()) && 
                        !tspJobDetailRunning.getId().equals(jobDetailShell.getId())){
                        continue;
                    }
                    
                    Channel runLastChannel = jobProcessManager.getJobDetailRunningLastChannel(jobDetailShell);
                    jobProcessManager.completeJobDetail(jobDetailShell.getJobName(), runLastChannel, jobDetailShell.getJobDetailName(),
                        jobDetailShell.getId());
                    LOG_SERVER.warn("SERVER-SCHEDULER: delete a offline job detail[{}.{}] id=[{}]", jobDetailShell.getJobName(),
                        jobDetailShell.getJobDetailName(), jobDetailShell.getId());
                }
            }
        } catch (Exception e) {
            LOG.error("SERVER-NETTY: reset offline job detail[{}] exception:", requestXml, e);
            String responseBody = String.format("reset offline job detail exception:%s", e.getMessage());
            response.setCode(ResponseCode.FAIL);
            response.setBody(responseBody.getBytes());
        }
        return response;
    }
    
}
